package com.ruoyi.flow.common.tools.mediaconverter.converter;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.ruoyi.flow.common.tools.mediaconverter.converter.ffmpeg.FfmpegInvoker;
import com.ruoyi.flow.common.tools.mediaconverter.converter.ffmpeg.FfmpegLocator;

import java.io.File;
import java.io.Serializable;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;

/**
 * 多媒体信息类
 */
public class MediaInfo implements Serializable {
	/**
	 * 多媒体文件路径
	 */
	private String mediaFilePath;

	@JsonIgnore
	private transient File mediaFile;

	/**
	 * 音频/视频时长，单位毫秒
	 */
	private long duration;

	/**
	 * 多媒体文件名称
	 */
	private String mediaFileName;

	public MediaInfo(File mediaFile) {
		checkNotNull(mediaFile);
		this.mediaFilePath = mediaFile.getAbsolutePath();
		this.mediaFile = mediaFile;
		checkState(this.mediaFile.exists(), "多媒体文件[{}]不存在！", mediaFilePath);
		this.mediaFileName = mediaFile.getName();
		this.duration = getDuration();
	}

	public File getMediaFile() {
		return mediaFile;
	}

	public String getMediaFileName() {
		return mediaFileName;
	}

	public long getDuration() {
		return getDuration(FfmpegLocator.getLocator());
	}

	/**
	 * 获取多媒体时长，单位为毫秒
	 * @param locator
	 * @return
	 */
	public long getDuration(FfmpegLocator locator) {
		checkNotNull(locator);
		FfmpegInvoker invoker = locator.createInvoker().addArg("-i").addArg(mediaFilePath);
		Pattern p2 = Pattern.compile("^\\s*Duration: (\\d\\d):(\\d\\d):(\\d\\d)\\.(\\d).*$", Pattern.CASE_INSENSITIVE);
		invoker.invoke();
		List<String> inString = invoker.getStdInputString();
		if (inString != null && !inString.isEmpty()) {
			for (String string : inString) {
				Matcher m = p2.matcher(string);
				if (m.matches()) {
					long hours = Integer.parseInt(m.group(1));
					long minutes = Integer.parseInt(m.group(2));
					long seconds = Integer.parseInt(m.group(3));
					long dec = Integer.parseInt(m.group(4));
					long duration = (dec * 100L) + (seconds * 1000L) + (minutes * 60L * 1000L)
							+ (hours * 60L * 60L * 1000L);
					return duration;
				}
			}
		}
		return 0L;
	}

	@Override
	public String toString() {
		return "fileName=" + mediaFileName + ",filePath=" + mediaFilePath + ",duration=" + duration;
	}

	public static void main(String[] args) {
		File mediaFile = new File("D:\\silk2mp3\\wxid_wy6qdk6y2bzt22.mp3");
		MediaInfo mediaInfo = new MediaInfo(mediaFile);
		System.out.println(mediaInfo.getDuration());
	}

}
